package br.com.dev.tcc.view.utilitarios;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import br.com.dev.tcc.R;
import br.com.dev.tcc.components.MonetaryTextView;
import br.com.dev.tcc.interfaces.UtilitariosItemView;

public class UtilitariosAlcoolGasolinaView implements UtilitariosItemView {

	private Context ctx;
	private View view;

	private MonetaryTextView etAlcool;
	private MonetaryTextView etGasolina;
	private TextView tvSugestao;

	public UtilitariosAlcoolGasolinaView(Context ctx) {

		this.ctx = ctx;

		LayoutInflater inflater = LayoutInflater.from(ctx);
		view = inflater.inflate(R.layout.utilitarios_alcoolxgas, null);

		setComponents();
		setListener();
	}

	private void setComponents() {

		etAlcool = new MonetaryTextView(
				(EditText) view.findViewById(R.id.etPrecoAlcool));
		etGasolina = new MonetaryTextView(
				(EditText) view.findViewById(R.id.etPrecoGas));
		tvSugestao = (TextView) view.findViewById(R.id.tvResult);
	}

	private void setListener() {

		Button bt = (Button) view.findViewById(R.id.btCalc);

		bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (checkCompletion())
					calculateSugestion();
				else
					showToast();
			}
		});
	}

	private boolean checkCompletion() {

		return etAlcool.getContent().length() > 0
				&& etGasolina.getContent().length() > 0;
	}

	/*
	 * Verifica se valor do alcool esta pelo menos 70% abaixo do valor da
	 * gasolina
	 */
	private void calculateSugestion() {

		double precoAlcool = etAlcool.getValue().doubleValue();
		double precoGasolina = etGasolina.getValue().doubleValue();

		if (precoAlcool / precoGasolina < 0.7)
			tvSugestao.setText(R.string.use_alcool);
		else
			tvSugestao.setText(R.string.use_gas);

		tvSugestao.setVisibility(View.VISIBLE);
		tvSugestao.requestFocus();
	}

	private void showToast() {

		Toast.makeText(ctx, R.string.preencha_dois, Toast.LENGTH_SHORT).show();
	}

	@Override
	public View getView() {

		return view;
	}
}
